package com.sf.pda;

import java.text.DecimalFormat;
import java.util.HashMap;

import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.sf.config.HadwareControll;
import com.sf.utils.UtilsLog;

public class PointManagerActivity extends BaseActivity implements
		OnClickListener {

	private EditText et_code, et_card_num, et_trade_name, et_price,
			et_discount, et_point;

	private Button btn_integral_binding, btn_userquery, btn_refund,
			btn_data_upload, btn_bd, btn_jb, btn_scan_tradecode,
			btn_scan_pointcode;

	public Handler mHandler = new MainHandler();
	private SoundPool soundpool;
	private HashMap<Integer, Integer> spMap;

	public boolean btn_scan = false;
	protected MediaPlayer mediaPlayer = null;
	HadwareControll Controll = null;

	// 标记扫的是哪个button
	private boolean Trade_Flag = false;
	private boolean Point_Flag = false;

	// 商品的原始价格
	private String originalPrice = "";

	// 标记第一次
	private boolean FirstTime = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.point);

		initView();
		registerListener();
	}

	public void initView() {
		// 初始化功能组件
		Controll = new HadwareControll(this);
		Controll.Open();

		mHandler = new MainHandler();
		HadwareControll.m_handler = mHandler;
		initBeepSound();

		et_code = (EditText) findViewById(R.id.et_code);
		et_card_num = (EditText) findViewById(R.id.et_card_num);
		et_trade_name = (EditText) findViewById(R.id.et_trade_name);
		et_price = (EditText) findViewById(R.id.et_price);
		et_discount = (EditText) findViewById(R.id.et_discount);
		et_point = (EditText) findViewById(R.id.et_point);

		btn_integral_binding = (Button) findViewById(R.id.btn_integral_binding);
		btn_userquery = (Button) findViewById(R.id.btn_userquery);
		btn_refund = (Button) findViewById(R.id.btn_refund);
		btn_data_upload = (Button) findViewById(R.id.btn_data_upload);
		btn_bd = (Button) findViewById(R.id.btn_bd);
		btn_jb = (Button) findViewById(R.id.btn_jb);

		btn_scan_tradecode = (Button) findViewById(R.id.btn_scan_tradecode);
		btn_scan_pointcode = (Button) findViewById(R.id.btn_scan_pointcode);
	}

	public void registerListener() {
		btn_bd.setOnClickListener(this);
		btn_jb.setOnClickListener(this);
		btn_integral_binding.setOnClickListener(this);
		btn_userquery.setOnClickListener(this);
		btn_refund.setOnClickListener(this);
		btn_data_upload.setOnClickListener(this);
		btn_scan_tradecode.setOnClickListener(this);
		btn_scan_pointcode.setOnClickListener(this);

		et_price.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				String price = s.toString().trim();
				// 单引号
				if (!TextUtils.isEmpty(price) && '.' == price.charAt(0)) {
					et_price.setText("");
				}
				if (!isCountRight(et_price)) {
					return;
				}
				UtilsLog.e("==price=", price);
				int i = 0;
				if (!TextUtils.isEmpty(price)) {
					i = (int) Double.parseDouble(price);
				}
				et_point.setText(i + "");

				// 清空之后复位
				if (TextUtils.isEmpty(s.toString())) {
					FirstTime = false;
					UtilsLog.e("==复位==", FirstTime + "");
					et_point.setText("");
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		et_discount.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// 记录第一次的数据
				if (!FirstTime) {
					originalPrice = et_price.getText().toString().trim();
					UtilsLog.e("original", originalPrice);
					FirstTime = true;
				}

				String discount = s.toString().trim();
				if (!TextUtils.isEmpty(discount) && '.' == discount.charAt(0)) {
					et_discount.setText("");
				}

				if (!isCountRight(et_discount)) {
					return;
				}

				// 进行打折运算 四舍五入
				if (!TextUtils.isEmpty(originalPrice)
						&& !TextUtils.isEmpty(discount)) {
					DecimalFormat df = new DecimalFormat("0.0");
					String curPrice = df.format((Double
							.parseDouble(originalPrice))
							* (Double.parseDouble(discount) / 10));
					et_price.setText(curPrice);
					// 设置积分
					if (curPrice.contains(".")) {
						UtilsLog.e("==curPrice==", curPrice);
						String ss = curPrice.substring(0, curPrice.indexOf("."));
						System.out.println(ss);
						et_point.setText(ss);
					} else {
						et_point.setText(curPrice);
					}
				}

				// 折扣复位
				if (TextUtils.isEmpty(s.toString())) {
					et_price.setText(originalPrice);
					UtilsLog.e("==zhekou==", originalPrice);
					if (originalPrice.contains(".")) {
						et_point.setText(originalPrice.subSequence(0,
								originalPrice.indexOf(".")));
					} else {
						et_point.setText(originalPrice);
					}
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

	}

	private boolean isCountRight(EditText ed) {
		String price = ed.getText().toString().trim();
		if (price.contains(".")) {
			String[] arr = price.split("\\.");
			if (arr.length == 2) {
				String arr1 = arr[1];
				if (arr1.length() > 1) {
					Toast.makeText(PointManagerActivity.this, "超出两位小数",
							Toast.LENGTH_SHORT).show();

					price = arr[0] + "." + arr1.substring(0, 1);

					ed.setText(price);
					ed.setSelection(price.length());

				}
			}
		}
		// if (Double.parseDouble(price) > 9999) {
		// return false;
		// }
		return true;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btn_integral_binding:
			break;
		case R.id.btn_userquery:
			break;
		case R.id.btn_refund:
			break;
		case R.id.btn_data_upload:
			Intent intent=new Intent(PointManagerActivity.this,UploadDataActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			break;
		case R.id.btn_bd:
			break;
		case R.id.btn_jb:
			break;
		case R.id.btn_scan_pointcode:
			Point_Flag = true;
			Trade_Flag = false;
			Controll.scan_start();
			break;
		case R.id.btn_scan_tradecode:
			Trade_Flag = false;
			Point_Flag = true;
			Controll.scan_start();
			break;
		default:
			break;
		}
	}

	private class MainHandler extends Handler {

		public void handleMessage(Message msg) {
			switch (msg.what) {

			case HadwareControll.BARCODE_READ: {
				String result = msg.obj + "\n";
				// lv.append(result);
				if (Trade_Flag) {
					et_code.append(result);
				}
				if (Point_Flag) {
					et_card_num.append(result);
				}
				playBeepSound();
				break;
			}
			default:
				break;
			}
		}
	};

	private void playBeepSound() {
		soundpool.play(spMap.get(1), 1, 1, 1, 0, 1);
	}

	private void initBeepSound() {
		soundpool = new SoundPool(1, // maxStreams参数，该参数为设置同时能够播放多少音效
				AudioManager.STREAM_MUSIC, // streamType参数，该参数设置音频类型，在游戏中通常设置为：STREAM_MUSIC
				0 // srcQuality参数，该参数设置音频文件的质量，目前还没有效果，设置为0为默认值。
		);
		spMap = new HashMap<Integer, Integer>();
		spMap.put(1, soundpool.load(this, R.raw.beep, 1));
	}

	protected void onDestroy() {
		Controll.Close();
		Controll.m_handler = null;
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10 || keyCode == KeyEvent.KEYCODE_F11)
				&& event.getRepeatCount() == 0) {

			Controll.scan_start();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10
				|| keyCode == KeyEvent.KEYCODE_F11) {
			Controll.scan_stop();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

}
